<?php

use OSS\Core\OssException;
use OSS\OssClient;
use Ramsey\Uuid\Uuid;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;

/**
 * 判断
 * @param $key
 * @param $value 被比较值
 * @param $html 输出的字符
 * @return string
 */
function eq_site_config($key,$value,$html)
{
    $config = Config::pull("site_config");
    if (array_key_exists($key,$config))
    {
        if ($config[$key] == $value)
        {
            return $html;
        }else {
            return "";
        }
    }else {
        return "";
    }
}

/**
 * 获取站点配置
 * @param $key
 * @return mixed|string
 */
function get_site_config($key)
{
    $config = Config::pull("site_config");
    if (array_key_exists($key,$config))
    {
        return $config[$key];
    }else {
        return "";
    }
}


/**
 * 随机文档
 * @param int $cid 资讯分类
 * @param int $limit 条数
 * @return array
 * @throws
 */
function get_random_doc_list($cid = 0, $limit = 10)
{

    $model = model('article');

    if ($cid != 0) {
        $model = $model->where(['cid' => $cid]);
    }

    $list = $model->orderRaw('rand()')->limit($limit)->select();
    if (!empty($list)) {
        $list = $list->toArray();
    }
    return $list;
}


/**
 * 获取微信扫码登录id
 * @return int
 */
function get_weixin_login_uuid()
{
    $weixin_uuid = rand(1, 99999);

    $key = "weixin_qrcode_login_uuid_" . $weixin_uuid;
    if (Cache::has($key)) {
        get_weixin_login_uuid();
    } else {
        Cache::set($key, $weixin_uuid, 60 * 5);
    }

    return $weixin_uuid;
}

/**
 * 显示缩略图
 * @param $item
 * @return string
 */
function showThumbnail($item)
{
    $sys = getSystem();
    return $sys['storage_url'] . '/' . $item['bid'] . '/thumbnail.png' . $sys['pic_param'];
}

/**
 * 显示预览图
 * @param $item
 * @return string
 */
function showPreviewImage($item)
{
    $sys = getSystem();
    $html = "";

    $code = get_http_code($sys['storage_url'] . '/' . $item['bid'] . "/svg/1.svg");

    if ($code == 200)
    {
        for ($i = 1; $i <= $item['preview']; $i++) {
            $html .= '<img alt="' . $item['title'] . '" src="' . $sys['storage_url'] . '/' . $item['bid'] . '/svg/' . $i . '.svg' . $sys['pic_param'] .'">';
        }
    }else {
        for ($i = 1; $i <= $item['preview']; $i++) {
            $html .= '<img alt="' . $item['title'] . '" src="' . $sys['storage_url'] . '/' . $item['bid'] . '/' . $i . '.png' . $sys['pic_param'] .' ">';
        }
    }

    return $html;
}

/**
 * 获取http状态码
 * @param $url
 * @return mixed
 */
function get_http_code($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    $return = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    return $return;
}
/**
 * 获取站点信息
 */
function getSystem()
{
    return Config::pull("site_config");
}

/**
 * 显示标签html
 * @param string $tags
 * @return string
 */
function showTags($tags = '')
{
    if (empty($tags)) return "";
    $tags = explode(",", $tags);
    $str = '';
    if (count($tags) > 0) {
        foreach ($tags as $tag) {
            $str .= '<a class="btn btn-light mr-2 disabled opacity-1">' . $tag . '</a>';
        }
    }
    return $str;
}

/**
 * 判断是否移动端域名
 * @param string $prefix
 * @return bool
 */
function isMobileDomain($prefix = 'm')
{
    $domain = str_replace(array('https://', 'http://'), '', strtolower(Request::domain()));
    $domain = explode('.', $domain);
    if (is_array($domain) && $domain[0] == $prefix) {
        return true;
    }
    return false;
}

/**
 * 上传文件到OSS
 * @param string $object 保存文件名
 * @param string $path 本地路径
 * @return bool|string
 */
function uploadFileToOSS($object = '', $path = '')
{

    try {
        $config = Config::pull("aliyun_oss");
        $ossClient = new OssClient($config['key_id'], $config['key_secret'], $config['endpoint']);
        return $ossClient->uploadFile($config['bucket'], $object, $path);
    } catch (OssException $e) {
        return $e->getMessage();
    }
}


/**
 * 获取分类所有子分类
 * @param $type
 * @param $pid
 * @param $limit
 * @return array|bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_category_children($pid, $limit, $is_home)
{
    $where = [];
    if ($pid != -1) {
        $where[] = ['pid', 'eq', $pid];
    }

    if ($is_home == 1) {
        $where[] = ['is_home', 'eq', 1];
    }

    $model = Db::name('category')->where($where);
    if ($limit != 0) {
        $model = $model->limit($limit);
    }

    $children = $model->order(['sort' => 'DESC'])->select();

    return array2tree($children);
}

/**
 * 根据分类ID获取內容列表（包括子分类）
 * @param int $cid 分类ID
 * @param int $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'content', 'thumb', 'reading', 'create_time'], (array)$filed);
    $map = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'create_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'create_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int $pid
 * @param int $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);

        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                if (!array_key_exists($child_key_name, $temp)) {
                    $temp[$child_key_name] = [];
                }
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
                        delete_dir_file($dir_name . DIRECTORY_SEPARATOR . $item);
                    } else {
                        unlink($dir_name . DIRECTORY_SEPARATOR . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}


/**
 * 采集地址
 * @param string $url 远程地址
 * @return mixed
 */
function spider_curl($url = '')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_REFERER, "http://m.360kan.com");
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, curl_headers());
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //允许重定向
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0");//模拟浏览器类型
    curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
    $html = curl_exec($curl);
    if (curl_errno($curl)) {
        print "Error: " . curl_error($curl);
    } else {
        curl_close($curl);
    }

    return $html;
}

/**
 * 随机ip
 * @return array
 */
function curl_headers()
{
    $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
    );

    $rand_key = mt_rand(0, 9);
    $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));


    $headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//    $headers['Accept-Encoding'] = "gzip, deflate";
    $headers['Accept-Language'] = "zh-CN,zh;q=0.8";
    $headers['Cache-Control'] = "no-cache";
    $headers['Connection'] = "keep-alive";
    $headers['Pragma'] = "no-cache";

//    $headers['CLIENT-IP'] = $ip;
//    $headers['X-FORWARDED-FOR'] = $ip;


    $headerArr = array();
    foreach ($headers as $n => $v) {
        $headerArr[] = $n . ':' . $v;
    }
    return $headerArr;
}


/**
 * 请求远程地址
 * @param string $url 地址
 * @param string $cookie
 * @return array
 */
function curl_url($url = '', $param = array(), $cookie = '')
{
    $header[] = "Content-type: application/x-www-form-urlencoded";
    $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

    if (!empty($cookie)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    if (!empty($param) && is_array($param)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    }

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8')); //构造IP
    curl_setopt($ch, CURLOPT_REFERER, "//www.taobao.com/ "); //构造来路

    $html = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);


    return array(
        'info' => $info,
        'data' => $html
    );
}

function arr2file($f, $arr = '')
{
    if (is_array($arr)) {
        $con = var_export($arr, true);
    } else {
        $con = $arr;
    }
    $con = "<?php\nreturn $con;\n?>";
    return write_file($f, $con);
}

function write_file($f, $c = '')
{
    $dir = dirname($f);
    if (!is_dir($dir)) {
        mkdirss($dir);
    }
    return @file_put_contents($f, $c);
}

function mkdirss($path, $mode = 0777)
{
    if (!is_dir(dirname($path))) {
        mkdirss(dirname($path));
    }
    if (!file_exists($path)) {
        return mkdir($path, $mode);
    }
    return true;
}

/**
 * 格式化文件大小
 * @param $size
 * @return string
 */
function formatSize($size)
{
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    if ($size == 0) {
        return ('未知');
    } else {
        return (round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
    }
}

/**
 * 生成随机数
 * @param int $length
 * @return string
 */
function make_rand($length = 8, $chars = "")
{
    if (empty($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}
